<template>
  <NuxtLayout name="admin" menuActive="/admin/class">
    <div class="card">
      <el-page-header @back="useRouter().go(-1)">
        <template #content>
          <el-input v-model="listForm.keyword" placeholder="请输入班级名称">
            <template #append>
              <el-button :icon="Search" @click="searchFn"></el-button>
            </template>
          </el-input>
        </template>
        <template #extra>
          <el-button @click="addFn">添加班级</el-button>
        </template>
      </el-page-header>
      <div style="height: 18px;"></div>
      <el-table :data="tableData" border show-overflow-tooltip>
        <el-table-column prop="serialNo" label="班级编号" />
        <el-table-column prop="name" label="班级名称" />
        <el-table-column prop="issue" label="开班日期" />
        <el-table-column prop="teacher.name" label="负责老师" />
        <el-table-column label="封面图" width="130">
          <template #default="scope">
            <el-image style="width: 100px;height: 100px;" :src="scope.row.imgs" :preview-src-list="[scope.row.imgs]"
              preview-teleported fit="cover" v-show="scope.row.imgs" />
          </template>
        </el-table-column>
        <el-table-column prop="brief" label="班级简介" />
        <el-table-column prop="totalHours" label="总学时" />
        <el-table-column prop="dayOfHours" label="每日最多学时" />
        <el-table-column prop="maxCount" label="学员上限数" />
        <el-table-column prop="userCount" label="班级学员总数" />
        <el-table-column prop="startTime" label="报名开始时间" />
        <el-table-column prop="endTime" label="报名截止时间" />
        <el-table-column label="是否结束" width="90">
          <template #default="scope">
            <el-tag type="success" v-show="scope.row.finished == 0">进行中</el-tag>
            <el-tag type="info" v-show="scope.row.finished == 1">已结束</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="examSetting.radioSize" label="单选题数量" />
        <el-table-column prop="examSetting.checkboxSize" label="多选题数量" />
        <el-table-column prop="examSetting.judgeSize" label="判断题数量" />
        <el-table-column prop="examSetting.radioScore" label="单选题分值" />
        <el-table-column prop="examSetting.checkboxScore" label="多选题分值" />
        <el-table-column prop="examSetting.judgeScore" label="判断题分值" />
        <el-table-column prop="examSetting.passScore" label="及格分" />
        <el-table-column prop="examSetting.fullScore" label="总分" />
        <el-table-column prop="examSetting.duration" label="时长(秒)" />
        <el-table-column label="操作" fixed="right" width="220">
          <template #default="scope">
            <a class="el-button el-button--small" :href="`/admin/certificate/class-${scope.row.id}.html`">查看证书</a>
            <a class="el-button el-button--primary el-button--small" :href="`/admin/student/${scope.row.id}`">学员</a>
            <el-button type="success" size="small" @click="editFn(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="card_pagin">
        <el-pagination background layout="prev, pager, next, total" :total="total" :page-size="listForm.pageSize"
          @change="pageChangeFn" />
      </div>
    </div>
    <MyForm :visible="formVisible" :forms="forms" :title="formTitle" @pick="formPickFn" />
  </NuxtLayout>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue'
import { classesPageList, addClasses, updateClasses } from '~/server/api'
import { formatTime } from '~/utils/utils'
import MyForm from './form'
// TDK
const prevHost = useRequestHeaders()["x-forwarded-proto"];
const host = useRequestHeaders()["host"];
const fullPath = useRoute()["fullPath"];
useSeoMeta({
  title: "技考邦_班级管理",
  keywords: "技考邦,班级管理",
  description: "技考邦，班级管理。",
  ogTitle: "技考邦_班级管理",
  ogDescription: "技考邦，班级管理。",
  ogType: "article",
  ogUrl: `${prevHost}://${host}${fullPath}`,
});
const listForm = ref({
  pageNum: 1,
  pageSize: 20,
  keyword: ''
})
const tableData = ref([])
const total = ref(0)
const getList = async () => {
  let { data: listRes } = await useAsyncData('', () => useServerRequest(classesPageList, {
    method: 'post',
    body: JSON.stringify(listForm.value)
  }))
  if (listRes.value && listRes.value.errno === 0) {
    tableData.value = listRes.value.result.list;
    total.value = listRes.value.result.total;
  }
}
getList()
// 搜索
const searchFn = () => {
  listForm.value.pageNum = 1;
  getList()
}
// 分页
const pageChangeFn = (val) => {
  listForm.value.pageNum = val;
  getList()
}
// 生成二维码
const qrcodeVisible = ref(false)
const qrocdeBase64 = ref('')
const qrcodeFn = (val) => {
  let opts = {
    errorCorrectionLevel: "L", //容错级别
    type: "image/png", //生成的二维码类型
    quality: 0.3, //二维码质量
    margin: 2, //二维码留白边距
    width: 256, //宽
    height: 256, //高
    text: "", //二维码内容
    color: {
      dark: "#000", //前景色
      light: "#fff", //背景色
    }
  };
  QRCode.toDataURL(`/student/${val.id}`, opts, (err, url) => {
    if (err) throw err;
    qrocdeBase64.value = url;
    qrcodeVisible.value = true;
  })
}
// 添加
const forms = ref({
  id: null,
  subjectId: null,
  courseIds: [],
  name: '',
  issue: formatTime(new Date().getTime()),
  imgs: '',
  brief: '',
  teacherId: null,
  totalHours: 0,
  dayOfHours: 0,
  maxCount: 1000,
  startTime: formatTime(new Date().getTime()),
  endTime: '',
  finished: false,
  examSetting: {
    randomExercise: true,
    radioSize: 50,
    checkboxSize: 15,
    judgeSize: 20,
    radioScore: 1,
    checkboxScore: 2,
    judgeScore: 1,
    passScore: 80,
    duration: 7200
  },
  totalScore: 100,
  teacherName: ''
})
const formTitle = ref('')
const formVisible = ref(false)
const addFn = () => {
  forms.value.id = null;
  forms.value.subjectId = null;
  forms.value.courseIds = [];
  forms.value.name = '';
  forms.value.issue = formatTime(new Date().getTime());
  forms.value.imgs = '';
  forms.value.brief = '';
  forms.value.teacherId = null;
  forms.value.totalHours = 0;
  forms.value.dayOfHours = 0;
  forms.value.maxCount = 1000;
  forms.value.startTime = formatTime(new Date().getTime());
  forms.value.endTime = '';
  forms.value.finished = false;
  forms.value.examSetting = {
    randomExercise: true,
    radioSize: 50,
    checkboxSize: 15,
    judgeSize: 20,
    radioScore: 1,
    checkboxScore: 2,
    judgeScore: 1,
    passScore: 80,
    duration: 7200
  };
  forms.value.totalScore = 100;
  forms.value.teacherName = '';
  formTitle.value = '添加班级';
  formVisible.value = true;
}
// 编辑
const editFn = (val) => {
  forms.value.id = val.id;
  forms.value.subjectId = val.subjectId;
  forms.value.courseIds = val.courseIds;
  forms.value.name = val.name;
  forms.value.issue = val.issue;
  forms.value.imgs = val.imgs;
  forms.value.brief = val.brief;
  forms.value.teacherId = val.teacherId;
  forms.value.totalHours = val.totalHours;
  forms.value.dayOfHours = val.dayOfHours;
  forms.value.maxCount = val.maxCount;
  forms.value.startTime = val.startTime;
  forms.value.endTime = val.endTime;
  forms.value.finished = val.finished;
  forms.value.examSetting = {
    randomExercise: val.examSetting.randomExercise,
    radioSize: val.examSetting.radioSize,
    checkboxSize: val.examSetting.checkboxSize,
    judgeSize: val.examSetting.judgeSize,
    radioScore: val.examSetting.radioScore,
    checkboxScore: val.examSetting.checkboxScore,
    judgeScore: val.examSetting.judgeScore,
    passScore: val.examSetting.passScore,
    duration: val.examSetting.duration
  };
  forms.value.totalScore = val.examSetting.fullScore;
  forms.value.teacherName = val.teacher ? val.teacher.name : '';
  formTitle.value = '编辑班级';
  formVisible.value = true;
}
// 取消 确认
const formPickFn = async (e) => {
  if (e.form) {
    const loading = ElLoading.service({ text: '请求中...', target: document.querySelector('.el-dialog') })
    let url = e.form.id ? updateClasses : addClasses;
    let classRes = await useServerRequest(url, {
      method: 'post',
      body: JSON.stringify(e.form)
    })
    if (classRes.errno === 0) {
      ElMessage({
        message: e.form.id ? '修改成功' : '添加成功',
        type: 'success'
      })
      getList()
      formVisible.value = e.visible;
    }
    loading.close()
    return false;
  }
  formVisible.value = e.visible;
}
</script>

<style lang="less" scoped>
.card {
  background: #FFFFFF;
  border-radius: 10px;
  border: 1px solid #EEEEEE;
  padding: 35px 25px;

  &_pagin {
    margin-top: 30px;
    display: flex;
    justify-content: center;
  }
}
</style>